package loan.calc.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

    /**
     * 动态数据源名称上下文
     */
    private static final ThreadLocal<String> DATASOURCE_CONTEXT_KEY_HOLDER =
            ThreadLocal.withInitial(() -> DataSourceNames.MASTER);


    /**
     * 设置/切换数据源
     */
    public static void setCurrent(String name) {
        DATASOURCE_CONTEXT_KEY_HOLDER.set(name);
    }

    /**
     * 获取数据源名称
     */
    public static String getCurrent() {
        String key = DATASOURCE_CONTEXT_KEY_HOLDER.get();
        return key == null ? DataSourceNames.MASTER : key;
    }

    /**
     * 删除当前数据源名称
     */
    public static void clear() {
        DATASOURCE_CONTEXT_KEY_HOLDER.remove();
    }

    /**
     * Determine the current lookup key. This will typically be
     * implemented to check a thread-bound transaction context.
     * <p>Allows for arbitrary keys. The returned key needs
     * to match the stored lookup key type, as resolved by the
     * {@link #resolveSpecifiedLookupKey} method.
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return getCurrent();
    }

    public DataSource getAcuallyDataSource() {
        Object lookupKey = determineCurrentLookupKey();
        if (null == lookupKey) {
            return this;
        }
        return this.determineTargetDataSource();
    }

}
